#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Import the Flask Framework
from flask import Flask

from flask import Flask, session, redirect, url_for, escape, request
from flask import render_template
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.

# latest changes
latest_changes = "2-2-2015"

# our sample data
foods = {}
foods["banana"] = "A delicious and tasty treat!"
foods["dirt"]   = "Not delicious. Not tasty. DO NOT EAT!"
foods["cheese"]   ="Cheese is one of the known foods"

import codecs

import re

# read rumi jawi data
f = codecs.open("rumi-jawi-unicode.txt", mode="r", encoding='utf-8')
rjDict1 = {}
rjDict2 = {}

for line in f:
  line = line.strip()
  r, j = line.split(",")
  if r not in rjDict1:
    rjDict1[r] = j
  else:
    rjDict2[r] = j


###norvig
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def edits1(word):
  splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]
  deletes    = [a + b[1:] for a, b in splits if b]
  transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
  replaces   = [a + c + b[1:] for a, b in splits for c in alphabet if b]
  inserts    = [a + c + b     for a, b in splits for c in alphabet]
  return set(deletes + transposes + replaces + inserts)
##
def edits2(word):
  return set(e2 for e1 in edits1(word) for e2 in edits1(e1))


# @app.route('/')
# def hello():
#     # """Return a friendly HTTP greeting."""
#     # return 'Hello World! Flask'
# def index():
#     return 'Index Page'

# @app.route('/')
# def index():
#     if 'username' in session:
#         return 'Logged in as %s' % escape(session['username'])
#     return 'You are not logged in'



@app.errorhandler(404)
def page_not_found(e):
    """Return a custom 404 error."""
    return 'Sorry, Nothing at this URL.', 404


@app.errorhandler(500)
def page_not_found(e):
    """Return a custom 500 error."""
    return 'Sorry, unexpected error: {}'.format(e), 500

@app.route('/hello')
def hello():
	return redirect(url_for('hello2'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['rumi'] = request.form['rumi']
        return redirect(url_for('index'))
    return '''
        <form action="" method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
     '''

@app.route('/logout')
def logout():
    # remove the username from the session if it's there
    session.pop('username', None)
    return redirect(url_for('index'))

@app.route('/index_rumijawi')
def index_rumijawi():
	if 'rumi' in session:
		return 'rumi %s' % rumi
	return '''
		<form action="" method="post">
		<p><input type=text name=rumi>
		<p><input type=submit value=transliterate>
		</form>
	'''



# @app.route('/rumijawi',methods=['GET','POST'])
# def rumijawi():
# 	if request.method == 'POST':
# 		session['rumi'] = request.form['rumi']
# #		return redirect(url_for('index_rumijawi'))	
# 	return '''
# 		<form action="" method="post">
# 		<p><input type=text name=rumi>
# 		<p><input type=submit value=transliterate>
# 		</form>
# 	'''

@app.route('/authorname')
def authorname():
	author = "zamri"
	name = "mohd"
	return render_template('index.html', author=author, name=name)

@app.route('/pizza2')
def pizza2():
	return render_template('pizza.html')

@app.route('/pizza1', methods= ['GET','POST'])
def pizza1():
	return '''
	This is pizza 1
	<p>
	<form action="post.html" method="post">
	<input type="text" name="email"></input>
	<p>
	<input type="radio" name="topping" value="supreme">Supreme</input>
 	<input type="radio" name="topping" value="vegetarian">Vegetarian</input>
 	<input type="radio" name="topping" value="hawaiian">Hawaiian</input>
 	<p>
 	<select name="sauce">
  	<option value="tomato">Tomato</option>
  	<option value="barbeque">Barbeque</option>
  	<option value="mayonnaise">Mayonnaise</option>
  	<option value="secret">Secret Sauce</option>
	</select>
	<p>
	<option selected="selected" value="secret">Secret Sauce</option>
	<p>
	<input type="checkbox" name="extra_cheese" value="1">Extra Cheese</input>
	<input type="checkbox" name="gluten_free" value="1">Gluten Free Base</input>
	<p>
	<textarea name="delivery" cols="50" rows="4"></textarea>
	<p>
	<input type="submit" value="Send my Order">
	</form>
	'''

@app.route('/anchovy')
def anchovy():
	return render_template('anchovy.html')


@app.route('/anchovyorder', methods = ['POST'])
def anchovyorder():
    email = request.form['email']
    print("The email address is '" + email + "'")
    return redirect('/')

#return redirect('/anchovy')

@app.route('/email')
def email():
	return redirect(url_for('emailform'))




@app.route('/mula')
def mula():
	return render_template('mula.html')

@app.route('/signup', methods = ['POST'])
def signup():
    email = request.form['email']
    # print not working on browser
    print "hello world"
    print("The email address is in signup function '" + email + "'")
    if email == "":
    	return render_template('mula.html')
    else:
    	return render_template('mula.html', email = email)

@app.route('/transliterate', methods = ['POST'])
def transliterate():
    rumi = request.form['rumi']
    # print not working on browser
    #print "hello world"
    #print("The email address is in signup function '" + email + "'")

    if rumi in rjDict1:
    	if rumi in rjDict2:
    		return render_template('transliterate.html', rumi = rumi, jawi = rjDict1[rumi], jawi2 = rjDict2[rumi],latest_changes=latest_changes)
    	return render_template('transliterate.html', rumi = rumi, jawi = rjDict1[rumi],latest_changes=latest_changes)
    else:
    	guest1 = edits1(rumi)
    	guest2 = []
    	for c in guest1:
    		if c in rjDict1:
    			guest2.append(c)
    	return render_template('not_found_transliterasi.html', rumi = rumi, guesses = guest2,latest_changes=latest_changes)
    # return pass
# set the secret key.  keep this really secret:

@app.route('/')
@app.route('/rumijawi')
def rumijawi():
	return render_template('rumijawi.html',latest_changes=latest_changes)

@app.route('/rumijawi_paragraph')
def rumijawi_paragraph():
	return render_template('rumijawi_paragraph.html',latest_changes=latest_changes)

@app.route('/transliterate_paragraph', methods = ['POST'])
def transliterate_paragraph():
    rumi = request.form['rumi']
    rumi = re.split('(\W+)',rumi)

    # print not working on browser
    #print "hello world"
    #print("The email address is in signup function '" + email + "'")

    punc =      ['.',',','?',':',';','-','(',')','!','`','"','“']
    punc_arab = ['.',',','؟',':','؛','-',')','(','!','’','"','"']


    paragraph_rumi = []
    paragraph_jawi = []
    rj = {}
    for r in rumi:
    	if r.lower().strip() == '':
    		continue
    	if r.lower().strip() == ' ':
    		continue
    	if r.lower() in rjDict1:
    		paragraph_rumi.append(r)
    		paragraph_jawi.append(rjDict1[r.lower()])
    		rj[r] = rjDict1[r.lower()]
    	elif r.strip() in punc:
    		paragraph_rumi.append(r.strip())
    		paragraph_jawi.append(punc_arab[punc.index(r.strip())])
    	else:
    		paragraph_rumi.append(r)
    		paragraph_jawi.append('؟'.decode('utf-8'))
    return render_template('transliterate_paragraph.html', paragraph_rumi = paragraph_rumi,paragraph_jawi = paragraph_jawi,
        latest_changes=latest_changes)
    # return pass

@app.route('/overview')
def overview():
	return render_template('overview.html', latest_changes=latest_changes)

@app.route('/teknikal')
def teknikal():
	return render_template('teknikal.html', latest_changes=latest_changes)


@app.route('/hubungi')
def hubungi():
    return render_template('hubungi.html',latest_changes=latest_changes)

app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'